<template>
	<up-popup :show="show" v-if="show" mode="bottom"  :round="10" @close="handleClose" @open="handleOpen">
		<view class="up-popup-continar">
			<view class="title">
				发布拼桌
			</view>
			<image @click="handleClose" class="close" src="https://oss.jtmckj.com/drifbottle/icon-close.png" mode="">
			</image>
			<view class="thrwo-continar">
			<!-- 	<view class="title-tr">
					选择颜色
				</view> -->
			<!-- 	<view class="throw-flex">
					<view class="throw-item" :class="{ 'throw-itemboder': index === defutOne }"
						v-for="(item,index) in throwList" :key="index" @click="throwChange(index,item)">
						   <image class="lfimg" :src="item.lfimg" mode=""></image>
						<view class="item-title">
							{{item.name}}
						</view>
					</view>
				</view> -->
				<view class="form-flex " style="margin: 40rpx 0 25rpx 0;">
					<view class="form-label">
						我是：
					</view>
					<view class="selet-continar">
						<view class="selet-item" v-for="(item,index) in checkList" :key="index"
							@click="selectChange(index)">
							<view class="select-img" :class="{'select-imgAC': index === defutcheck}"></view>
							<view class="title-se">
								{{item}}
							</view>
						</view>
					</view>
				</view>

				<view class="container">
					<u-form ref="uFormRef" :model="form" :rules="rules">
						<u-form-item class="right-align-label" label="" prop="value1" label-width="160rpx" >
							<view class="form-flex">
								  <view class="form-label">
								  	昵称：
								  </view>
								  <u-input v-model="form.value1" disabled placeholder="请输入昵称" />
							</view>
						</u-form-item>
						<u-form-item class="right-align-label" label="" prop="age" label-width="160rpx" >
							<view class="form-flex" style="transform: translateY(-9rpx);">
								  <view class="form-label">
								  	年龄：
								  </view>
							          <u-input v-model="form.age" placeholder="请输入或选择年龄" />
								  </view>
						</u-form-item>
						<view class="tabs-select-continar">
							<view class="tabs-select-item colbg1" v-if="defutcheck == 0"  :class=" `colbg${index}`"
								v-for="(item,index) in ageList" :key="index" @click="ageChange(item)">
								{{item}}
							</view>
							<view class="tabs-select-item colbg1" v-if="defutcheck == 1"  :class=" `colbg${index}`"
								v-for="(item,index) in ageList2" :key="index" @click="ageChange2(item)">
								{{item}}
							</view>
						</view>
						<u-form-item class="right-align-label" label="" prop="msg" label-width="160rpx">
							<view class="form-flex">
								  <view class="form-label">
								  	我的愿望：
								  </view>
								  <up-textarea :maxlength="100" v-model="form.msg" placeholder="请输入或选择愿望"
								  	count></up-textarea>
								  </view>
								  
					
						</u-form-item>
						<view class="">
							<view class="tabs-select-continar">
								<view class="tabs-select-item colbg1" :class=" `colbg${index}`"
									v-for="(item,index) in ywtabList" :key="index" @click="ywtabChange(item)">
									{{item}}
								</view>
							</view>
							<view class="" style="display: flex;padding-left: 150rpx;margin-top: 10rpx	;">
								<view class="new-item colbg3" @click="getBottleMsg">
									换一批
								</view>
							</view>
						</view>
						
						<u-form-item class="right-align-label" label="" prop="code" label-width="160rpx">
							<view class="form-flex">
								  <view class="form-label">
								  	我的桌号：
								  </view>
								  <!-- #ifndef APP-NVUE -->
								  <up-input disabled  placeholder="请扫码桌号" v-model="form.code">
								  <!-- #endif -->
								  	<!-- #ifdef APP-NVUE -->
								  	<up-input disabled placeholder="请扫码桌号" v-model="form.code">
								  	<!-- #endif -->
								  		<template #suffix>
								  			<image @click="scanCodeChange" class="code-erm"
								  				src="https://oss.jtmckj.com/drifbottle/code-erm.png" mode=""></image>
								  		</template>
								  	<!-- #ifndef APP-NVUE -->
								  	</up-input>
								  	<!-- #endif -->
								  <!-- #ifdef APP-NVUE -->
								  </up-input>
								  <!-- #endif -->
								  
								  </view>
						</u-form-item>
						<view class="form-flex" style="margin-top: 15rpx;">
							<view class="form-label">
								上传照片：
							</view>
							<view class="" style="font-weight: 500;font-size: 26rpx;color: #666666;">
								（上传照片更受大家欢迎哦）
							</view>
						</view>
						<!-- 图片上传start -->
						<view class="form-flex" style="margin-top: 15rpx;">
							<view class="form-label">
							</view>
							<view class="">
								<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
									multiple :maxCount="1">
									<image class="up-zdy-img" src="https://oss.jtmckj.com/drifbottle/positive.png"
										mode="widthFix"></image>
								</up-upload>
							</view>
						</view>
						<!-- 图片上传end -->
						<view class="primary-btn" @click="handleSubmit">
							确认
						</view>
					</u-form>
				</view>
			</view>
		</view>
		<!-- 扫码start -->
		    <!--     <view class="scanCode" v-if="showScan">
		         	<mumu-get-qrcode @success='qrcodeSucess' @error="qrcodeError"></mumu-get-qrcode>
		         </view> -->
		<!-- 扫码end -->
	</up-popup>
</template>

<script setup>
	import {ref,watch } from 'vue';
	import { http } from '@/api/pzApi/http/api.js';
	import { HFiveMemberAppObjProcess } from '@/api/public.js'
	import { getWeChatJsSDKConfig, _ExtractParamsFromPath} from '@/until/tools.js'
    import BASE_URL from '@/api/pzApi/http/env.js'
	import wx from "weixin-js-sdk";
	
	// 定义接受的属性
	const props = defineProps({
		show: {
			type: Boolean,
			default: false
		},
		content: {
			type: String,
			default: '人生若只如初见，何事秋风悲画扇'
		}
	});
 
    const globalData = uni.getStorageSync('userInfo')
	console.log(globalData,'globalData----------xxxxxxxxxxxxx')
	 
	 const SDKConfig = ref({})
	 onLoad((options) => {
	 	getWeChatJsSDKConfig().then(resking => {
	 		SDKConfig.value = resking
	 	})
	 });
	 
	// 定义事件处理函数
	const handleClose = () => {
		emit('close');
	};

	const handleOpen = () => {
		emit('open');
		getBottleSexAge()
		getBottleMsg()
	};
	
	
	//获取性别年龄配置	
	const getBottleSexAge =async ()=> {
		  const params = {
		  		  "functionName": "getBottleSexAge",
		  		    "orgCode":globalData.orgCode,
		  		    contentData: {}
		  }	
		     try {
		        const res = await http.post('/AppMemberMallProcess', params);
				const [array1, array2] = res.content.rowData.split('|').map(item => item.split(','));
				ageList.value =array1
				ageList2.value =array2
		        console.log('res1111', res);
		      } catch (error) {
		        console.error('Error during login:', error);
		      }
	}
	
	const getBottleMsg = async ()=> {
		  const params = {
		  		  "functionName": "getBottleMsg",
		  		    "orgCode":globalData.orgCode,
		  		    contentData: {}
		  }	
		     try {
		        const res = await http.post('/AppMemberMallProcess', params);
				const array = res.content.rowData.split('|');
		        ywtabList.value = array
		      } catch (error) {
		        console.error('Error during login:', error);
		      }
	}

	const throwList = ref([{
			name: '优雅黄',
			img: 'https://oss.jtmckj.com/drifbottle/throw-item1.png',
			lfimg: 'https://oss.jtmckj.com/drifbottle/lfimg1.png'
		},
		{
			name: '魅力蓝',
			img: 'https://oss.jtmckj.com/drifbottle/throw-item2.png',
			lfimg: 'https://oss.jtmckj.com/drifbottle/lfimg2.png'
		},
		{
			name: '可爱粉',
			img: 'https://oss.jtmckj.com/drifbottle/throw-item3.png',
			lfimg: 'https://oss.jtmckj.com/drifbottle/lfimg3.png'
		},
		{
			name: '冷峻黑',
			img: 'https://oss.jtmckj.com/drifbottle/throw-item4.png',
			lfimg: 'https://oss.jtmckj.com/drifbottle/lfimg4.png'
		}
	])

	const defutOne = ref(0)
	const defutpzValue = ref(throwList.value[0].name)
	const throwChange = (index,item) => {
		defutOne.value = index
		defutpzValue.value = item.name
	}


	const checkList = ref(['美女', '帅哥'])
	const defutcheck = ref(0)
	const selectChange = (index) => {
		defutcheck.value = index
	}

	const ageList = ref([])
	const ageChange = (v) => {
		form.value.age = v
	}
	const ageList2 = ref([])
	const ageChange2 = (v) => {
		form.value.age = v
	}
	
	const ywtabList = ref([])
	const ywtabChange = (v) => {
		form.value.msg = v
	}
	/* 图片上传----------------------------------------------------------------------- */
	
	const fileList1 = ref([]);
	
	// 删除图片
	const deletePic = (event) => {
	  fileList1.value.splice(event.index, 1);
	};
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fileList1.value.length;
	  lists.map((item) => {
	    fileList1.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  console.log(lists,'lists')
	  for (let i = 0; i < lists.length; i++) {
	    const result = await uploadFilePromise(lists[i].url,lists[i].name);
	    let item = fileList1.value[fileListLen];
	    fileList1.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: result,
	    });
	    fileListLen++;
	  }
	};
	
	const uploadFilePromise = (url,name) => {
	  return new Promise((resolve, reject) => {
		   console.log(url,'resolve-')
	    let a = uni.uploadFile({
	      url: BASE_URL + '/Upload', // 仅为示例，非真实的接口地址
	      filePath: url ,
	      name: 'data',
			formData: {
				requestId: Math.random().toString(36).substr(2, 8),
				total: 1,
				fileName:name,
				objName: 'Mini',
				orgCode: '004',
				uploadType: 'OSS',
				bucketName: 'jtmc',
			},
	      success: (res) => {
			  console.log(res,'x')
			  
			  let data = JSON.parse(res.data)
			  console.log(data,'xxxxxxxxx')
			  
	        // setTimeout(() => {
	          resolve(data.content.urlPath);
	        // }, 500);
	      },
	    });
	  });
	};

	/* 图片上传----------------------------------------------------------------------- */

	const scanResult = ref('');
	
	const roomCode = ref('')
	
	const showScan = ref(false)
    const qrcodeSucess = (data)=> {
    		const match2 = data.match(/[?&]code=([^&]+)/);
    		roomCode.value = match2 ? match2[1] : null;
    		
    		uni.showToast({
    			title: '扫码成功',
    			icon: 'success',
    			duration: 2000
    		})
			if(roomCode.value) {
				  getroomCode()
			}
    		showScan.value = false
    	}
    	
    	const qrcodeError =(err) => {
    		uni.showToast({
    			title:'识别错误',
    			icon: 'success',
    			duration: 2000
    		})
    	}

	// 扫码功能
	const scanCodeChange = () => {
          wx.config({
          	debug: false, // 开启调试模式,
          	appId: SDKConfig.value.appId, // 必填，企业号的唯一标识
          	timestamp: SDKConfig.value.timestamp, // 必填，生成签名的时间戳
          	nonceStr: SDKConfig.value.nonceStr, // 必填，生成签名的随机串
          	signature: SDKConfig.value.signature, // 必填，签名
          	jsApiList: ['scanQRCode'], // 必填，需要使用的JS接口列表
          });
		  
		  wx.ready((res) => {
		  	wx.scanQRCode({
		  		needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
		  		scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
		  		success: function(res) {
		  			if (res.resultStr) {
		  				const options = _ExtractParamsFromPath(res.resultStr);
		  				if (!options.code) {
		  					uni.showToast({ title: "二维码出错", icon: "none" });
		  					return
		  				} 
						if(options.code) {
							  getroomCode(options.code)
						}
		  				
		  			} 
		  		},
		  		fail: function(response) {
		  			uni.showToast({ title: "请扫描正确的二维码", icon: "none" });
		  		},
		  	});
		  }) 
	};


   //获取房台号
   const  getroomCode = async (code)=> {
	   const params = {
	   		  "functionName": "GetRoomName",
	   		    contentData: {
	   			     roomCode:code
	   		     }
	   }	
	      const res = await http.post('/AppMemberMallProcess', params);
		    console.log(res,'房台号名称--------------')
			 if(res.opFlag == "1") {  
			     form.value.code = res.content.rowData.roomName
			 }
   }

	// 表单数据
	const form = ref({
		value1: globalData.name || '',
		age:'',
		msg: '',
		code: ''
	})

	// 验证规则
	const rules = {
		value1: [{
			required: false,
			message: '请输入昵称',
			trigger: 'blur'
		}],
		age: [{
			required: true,
			message: '请选择年龄',
			trigger: 'blur'
		}],
		msg: [{
			required: true,
			message: '请输入或选择愿望',
			trigger: 'blur'
		}],
		code: [{
			required: false,
			message: '请扫码桌号',
			trigger: 'blur'
		}]
	}



	// 定义事件发射器
	const emit = defineEmits(['close', 'open']);

	// 表单引用
	const uFormRef = ref(null);
	
	
	// 提交表单
	const handleSubmit =  (done) => {
		uFormRef.value.validate().then(async valid => {
			if (valid) {
				const params = {
						  "functionName": "bottleThrow",
						    "orgCode":globalData.orgCode,
						    contentData: {
							  sessionid: uni.getStorageSync('sessionId'),
							  type: "0",
							  memberCode: globalData.userCode,//会员编码
							   memberName: globalData.name,
							  roomCode: roomCode.value,//有房台的需要填写
							  roomName:  form.value.code,//有房台的需要填写
							  bottleType: defutpzValue.value,//pingzi类型
							  msg: form.value.msg,//rengpingzi愿望
							  image:defutcheck.value == 1 ? 'https://oss.jtmckj.com/drifbottle/addimg.png' : 'https://oss.jtmckj.com/drifbottle/addimgnrr.png',
							  sex:defutcheck.value == 1 ? '男' : '女'  , //性别 1男0女
							  age:form.value.age, //年纪 11纯情少男，12霸道总裁，13成熟大叔  01豆蔻少女，02经典美女，03风情少妇
							  logo:globalData.attachment ? globalData.attachment : 'https://oss.jtmckj.com/wmp/images/common/i_default_avatar.png',
						     }
				}	
				
				if(fileList1.value.length > 0) {
					params.contentData.image = fileList1.value[0].url
				}
				   try {
					   console.log(params,'params--------')
				      const res = await http.post('/AppMemberMallProcess', params);
						  
					  if(res.opFlag == "0") {
						  uni.$u.toast(res.opMsg)
						  if(res.opMsg== '尚未开台') {
							  form.value.code = ''
							  uni.showToast({
							  	title: '请扫开台的桌号',
							  	icon: 'none',
							  	duration: 2000
							  })
						    }
						  // form.value = {}
						  // handleClose()
					  }
					  if(res.opFlag == "1") { 
						   uni.$u.toast("投掷成功")
						   form.value = {}
						   handleClose()
					  }
				      console.log('res', res);
				    } catch (error) {
				      console.error('Error during login:', error);
				    }
			} else {
				uni.$u.toast('校验失败')
			}
		}).catch(() => {
			// 处理验证错误  
			uni.$u.toast('校验失败')
		});
	}
	
	
</script>

<style scoped lang="less">
	.up-popup-continar {
		// position: absolute;
		// z-index: 9999 !important;
		/* min-height: 1360rpx; */
		z-index: 9999;
		padding: 0 48rpx 20rpx 48rpx;

		.title {
			text-align: center;
			font-weight: bold;
			font-size: 36rpx;
			color: #212121;
			height: 99rpx;
			line-height: 99rpx;
			border-bottom: 1rpx solid #E6E6E6;
		}

		.close {
			position: absolute;
			right: 48rpx;
			top: 32rpx;
			width: 36rpx;
			height: 36rpx;
		}

		.thrwo-continar {
			height: 1000rpx;
			overflow-y: auto;
			padding-top: 20rpx;

			.title-tr {
				font-weight: bold;
				font-size: 32rpx;
				color: #212121;
				margin-bottom: 23rpx;
			}

			.throw-flex {
				display: flex;
				justify-content: space-between;

				.throw-item {
					border: 1rpx solid transparent;
					position: relative;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 150rpx;
					height: 60rpx;
					background: #F7F7F7;
					border-radius: 8rpx;

					image {
						width: 64rpx;
						height: 78rpx;
					}

					.item-title {
						font-weight: 500;
						font-size: 28rpx;
						color: #666666;
					}

					.lfimg {
						width: 40rpx;
						height: 40rpx;
					}
				}
			}
		}

	}

	.throw-itemboder {
		background: #fff !important;
		border: 1rpx solid #ff9041 !important;
	}

	.form-flex {
		display: flex;
        align-items: center;
		.form-label {
			width: 160rpx;
			text-align: right;
			font-weight: 500;
			font-size: 28rpx;
			color: #212121;
		}

		.selet-continar {
			display: flex;

			.selet-item {
				display: flex;
				align-items: center;
				margin-right: 36rpx;

				.select-img {
					margin-right: 20rpx;
					width: 32rpx;
					height: 32rpx;
					background: url('https://oss.jtmckj.com/drifbottle/selet-item.png')no-repeat;
					background-size: 100% 100%;
				}

				.title-se {
					font-weight: 500;
					font-size: 28rpx;
					color: #666666;
				}

				.select-imgAC {
					background: url('https://oss.jtmckj.com/drifbottle/selet-ac.png')no-repeat;
					background-size: 100% 100%;
				}
			}
		}
	}

	.tabs-select-continar {
		padding-left: 150rpx;
		display: flex;
		/* justify-content: space-between; */
		flex-wrap: wrap;
		gap: 3rpx;

		.tabs-select-item {
			font-weight: 500;
			font-size: 20rpx;
			color: #212121;
			padding: 0 13rpx;
			height: 40rpx;
			line-height: 40rpx;
		}
	
	}
	.new-item  {
		font-weight: 500;
		font-size: 20rpx;
		color: #212121;
		padding: 0 20rpx;
		height: 40rpx;
		line-height: 40rpx;
	}

	.mt-mb40 {
		margin: 40rpx 0;
	}

	.colbg1 {
		background: #FFEECC;
	}

	.colbg2 {
		background: #EEFFCC;
	}

	.colbg3 {
		background: #FFFBCC;
	}

	.colbg4 {
		background: #CCFFCE;
	}

	.colbg5 {
		background: #FFCCFE;
	}

	.colbg6 {
		background: #CCD8FF;
	}

	.colbg7 {
		background: #CCFEFF;
	}

	.right-align-label .u-form-item__label {
		text-align: right;
	}

	.code-erm {
		position: relative;
		z-index: 9999;
		width: 48rpx;
		height: 48rpx;
	}

	.up-zdy-img {
		width: 120rpx;
		height: 120rpx;
	}

	.primary-btn {
		margin: 60rpx auto 0 auto;
		width: 480rpx;
		height: 80rpx;
		background: #f24479;
		border-radius: 40rpx;
		text-align: center;
		line-height: 80rpx;
		font-weight: bold;
		font-size: 32rpx;
		color: #FFFFFF;

	}

	.notbbf ::v-deep {
		background: none !important;
	}

	::v-deep .u-input,
	::v-deep .u-textarea {
		background: #e6e6e6;
		border-radius: 8rpx;

	}

	::v-deep .u-textarea {
		width: 430rpx;
		height: 120rpx;
	}

	::v-deep .u-border {
		border-width: 0 !important;
	}

	::v-deep .u-input {
		width: 430rpx;
		height: 80rpx;
	}

	::v-deep .u-form-item__body__left__content__label {
		justify-content: flex-end !important;
		font-weight: 500;
		font-size: 28rpx;
		color: #212121;
	}
	::v-deep .form-flex .u-input {
		background: #e7e7e7 !important;
	}
	.scanCode {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 99;
		height: 100%;
		width: 100%;
		background-color: rgba(0, 0, 0, 0.7);
	}
</style>